package com.flow.framework.core.service.properties.impl;

import com.flow.framework.common.error.SystemErrorCode;
import com.flow.framework.common.exception.CheckedException;
import com.flow.framework.core.service.properties.ISystemConfigPropertiesService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;

/**
 * 系统配置服务
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/2/5
 */
@Slf4j
@RequiredArgsConstructor
public class SystemConfigPropertiesServiceImpl implements ISystemConfigPropertiesService {

    /**
     * 占位符开始字符串
     */
    private static final String PLACE_HOLDER_START = "${";


    private final Environment environment;

    /**
     * @inheritDoc
     */
    @Override
    public String getConfigValue(String key, String defaultValue) {
        String property = environment.getProperty(key);
        if (null == property) {
            String placeHolder;
            if (key.startsWith(PLACE_HOLDER_START)) {
                placeHolder = key;
            } else {
                placeHolder = PLACE_HOLDER_START + key + "}";
            }
            property = environment.resolvePlaceholders(placeHolder);
            if (placeHolder.equals(property)) {
                return defaultValue;
            }
        }
        return property;
    }

    /**
     * @inheritDoc
     */
    @Override
    public String getConfigValue(String key) {
        String property = getConfigValue(key, null);
        if (null == property) {
            log.error("get config value error. key: {}", key);
            throw new CheckedException(SystemErrorCode.OBJECT_NOT_FOUND_ERROR);
        }
        return property;
    }

    /**
     * @inheritDoc
     */
    @Override
    public String resolvePlaceholders(String placeHolder) {
        return environment.resolvePlaceholders(placeHolder);
    }
}
